﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Web;

namespace Vincent._Excel
{
    /// <summary>
    /// 数据导出为 Csv 文件
    /// </summary>
    public class OutputCsv
    {
        /// <summary>
        /// 将结果集导出为Csv文件并下载
        /// </summary>
        /// <param name="dt"> 结果集 </param>
        /// <param name="FileName"> 文件名 </param>
        public static void DataTableToCvsAndDownload(DataTable dt, string FileName)
        {
            HttpResponse resp = HttpContext.Current.Response;                           //HttpContext.Current: 为当前 HTTP 请求获取 HttpContext 对象
            resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            resp.AppendHeader("Content-Disposition", "attachment;filename=" + FileName + ".csv");                                          //将一个 HTTP 头添加到输出流
            string colHeaders = "", ls_item = "";
            int i = 0;

            DataRow[] myRow = dt.Select("");

            //取得数据表各列标题，各标题之间以\t分割，最后一个列标题后加回车符 
            for (i = 0; i < dt.Columns.Count; i++)
            {
                if (i == dt.Columns.Count - 1)
                {
                    colHeaders += dt.Columns[i].Caption.ToString() + "\n";
                }
                else
                {
                    colHeaders += dt.Columns[i].Caption.ToString() + "\t";
                }
            }
            resp.Write(colHeaders);

            foreach (DataRow row in myRow)
            {
                for (i = 0; i < dt.Columns.Count; i++)
                {
                    if (i == dt.Columns.Count - 1)
                    {
                        ls_item += row[i].ToString() + "\n";
                    }
                    else
                    {
                        ls_item += row[i].ToString() + "\t";
                    }
                }

                resp.Write(ls_item);
                ls_item = "";
            }

            resp.End();
        }

    }
}
